package com.ljc.schedules;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ljc.entity.Post;
import com.ljc.service.PostService;
import com.ljc.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 定时器任务
 * 阅读量存储到数据库中
 *
 * @Author: ljc
 * @Date:Created in 20:40 2021/12/8
 */
@Component
public class ViewCountSyncTask {
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    PostService postService;

    @Scheduled(cron = "0/5 * * * * *")//每分钟同步
    public void task() {
        try {
            Set<String> keys = redisTemplate.keys("rank:post:*");
            List<String> ids = new ArrayList<>();
            for (String key : keys) {
                if (redisUtil.hHasKey(key, "post:viewCount")) {
                    ids.add(key.substring("rank:post:".length()));
                }
            }
            if (ids.isEmpty()) return;
            //需要更新阅读量
            List<Post> posts = postService.list(new QueryWrapper<Post>().in("id", ids));
            posts.stream().forEach(post -> {
                Integer viewCount = (Integer) redisUtil.hget("rank:post:" + post.getId(), "post:viewCount");
                post.setViewCount(viewCount);
            });
            if (posts.isEmpty()) return;
            //更新mysql数据库的viewCount
            boolean isSuccess = postService.updateBatchById(posts);
            //判断成功,显示消息
            if (isSuccess) {
                ids.stream().forEach((id) -> {
                    redisUtil.hdel("rank:post:" + id, "post:viewCount");
                    System.out.println(id + "---------------->同步成功");
                });
            }
        }
        catch (Exception e) {
            System.out.println("热议同步异常");
        }

    }
}
